package mspbots.data.tl.prod.jira.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultMessageModel;
import mspbots.data.tl.prod.jira.mapper.JiraTeamMapper;
import mspbots.data.tl.prod.jira.model.JiraTeam;
import mspbots.data.tl.prod.jira.service.JiraTeamService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Iterator;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@DS("master")
public class JiraTeamServiceImpl extends AbstractBaseServiceImpl<JiraTeamMapper, JiraTeam>
        implements JiraTeamService {

    @Override
    public void sync(ResultMessageModel model) {
        if (ObjectUtils.isEmpty(model.getEntity()) || !ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            log.error("jira.team.tl entry is null,or Action No Add");
            return;
        }
        Iterator<JsonNode> elements = model.getEntity().get("teams").elements();
        while (elements.hasNext()){
            JsonNode node = elements.next();
            JiraTeam data = JiraTeam.builder()
                    .teamId(node.get("id").asLong())
                    .title(node.get("title").asText())
                    .shareable(node.get("shareable").asBoolean())
                    .syncTime(LocalDateTime.now())
                    .build();
            data.setTenantCode(model.getTenantId());
            JiraTeam dbData = super.baseMapper.selectOne(Wrappers.<JiraTeam>lambdaQuery()
                    .eq(JiraTeam::getTenantCode, data.getTenantCode())
                    .eq(JiraTeam::getTeamId, data.getTeamId())
                    .last("limit 1"));
            if (ObjectUtils.isEmpty(dbData)) {
                super.baseMapper.insert(data);
            } else {
                data.setId(dbData.getId());
                super.baseMapper.updateById(data);
            }
        }
    }
}
